/// <reference path="../index.d.ts" />

export const setup = (callback: SetupCallback) => {
  let callbacks: Callbacks = {}

  window.jsBridge = {
    invoke(uuid, data = {}, callback) {
      callbacks[uuid] = callback
      window.nativeBridge?.postMessage(JSON.stringify({ uuid, data }))
    },
    receiveMessage(data: string) {
      const d: ReceiveMessageData = JSON.parse(data)
      callbacks[d.uuid]?.(d)
      setTimeout(() => delete callbacks[d.uuid], 1000)
    }
  }

  const timer = setInterval(() => {
    if (window.nativeBridge) {
      callback(window.nativeBridge)
      clearInterval(timer)
    }

    setTimeout(() => timer && clearInterval(timer), 60000)
  }, 1000)

  return () => {
    callbacks = {}
  }
}

export const call = (option: PromiseBridgeOption) => {
  const { name, params } = option || {}
  return new Promise(resolve => {
    window.jsBridge?.invoke?.(name, params, resolve)
  })
}

export default {
  setup,
  call
}
